/**
 * RBAC权限服务
 * 提供基于角色的权限控制相关功能
 * 
 * @deprecated 该文件已废弃！请使用以下替代方案：
 * - API层：使用 `authApi` 进行权限验证
 * - 工具类：使用 `RbacUtils` 进行前端权限辅助功能
 * - Hooks：使用 `useUserPermissions` 进行权限管理
 * 
 * 新的架构优势：
 * 1. 后端处理复杂权限逻辑，前端仅做状态管理
 * 2. API层统一管理，避免服务层冗余
 * 3. Hooks提供更好的状态管理和异步支持
 */

import type { 
  User, 
  Role, 
  Permission, 
  Department, 
  Team 
} from '../../../types/rbac';

/**
 * 权限服务类
 */
export class RbacService {
  
  /**
   * 计算用户权限
   */
  static calculateUserPermissions(
    user: User,
    allRoles: Role[],
    allPermissions: Permission[],
    allTeams: Team[],
    allDepartments: Department[]
  ): any {
    
    // 1. 获取用户直接分配的角色
    const directRoles = allRoles.filter(role => 
      user.roles?.some((userRole: any) => userRole.id === role.id)
    );
    
    // 2. 获取用户从所属团队继承的角色
    const userTeams = allTeams.filter(team =>
      user.teams?.some((userTeam: any) => userTeam.id === team.id)
    );
    
    const teamRoleIds = new Set<string>();
    userTeams.forEach(team => {
      // 团队角色继承逻辑已移除，团队不再直接拥有角色
    });
    
    const teamRoles = allRoles.filter(role => 
      teamRoleIds.has(role.id)
    );
    
    // 3. 合并所有角色（去重）
    const allRoleIds = new Set([
      ...directRoles.map(r => r.id),
      ...teamRoles.map(r => r.id)
    ]);
    
    const allUserRoles = allRoles.filter(role => allRoleIds.has(role.id));
    
    // 4. 计算所有权限（去重）
    const allPermissionIds = new Set<string>();
    allUserRoles.forEach(role => {
      role.permissions.forEach(permId => allPermissionIds.add(permId));
    });
    
    const userPermissions = allPermissions.filter(perm => 
      allPermissionIds.has(perm.id)
    );
    
    return {
      userId: user.id,
      directRoles,
      teamRoles,
      allRoles: allUserRoles,
      allPermissions: userPermissions,
      accessibleMenus: [] // 这里需要根据权限计算可访问的菜单
    };
  }
  
  /**
   * 检查用户是否拥有指定权限
   */
  static hasPermission(
    user: User,
    permissionCode: string,
    allRoles: Role[],
    allTeams: Team[],
    allDepartments: Department[],
    context?: any // 权限验证上下文
  ): boolean {
    const userPermissions = this.calculateUserPermissions(
      user, 
      allRoles, 
      [], 
      allTeams, 
      allDepartments
    );
    
    // 检查是否为超级管理员
    const isSuperAdmin = userPermissions.allRoles.some((role: any) =>
      role.permissions.includes('*')
    );
    
    if (isSuperAdmin) {
      return true;
    }
    
    // 基础权限检查（向后兼容）
    const hasBasicPermission = userPermissions.allRoles.some((role: any) =>
      role.permissions.includes(permissionCode)
    );
    
    if (!hasBasicPermission) {
      return false;
    }
    
    // 如果没有上下文或权限没有条件，直接返回基础权限结果
    if (!context) {
      return hasBasicPermission;
    }
    
    // 获取具体的权限对象进行条件验证
    return this.validatePermissionConditions(
      user,
      permissionCode,
      userPermissions.allPermissions,
      context,
      allTeams,
      allDepartments
    );
  }

  /**
   * 验证权限条件
   */
  private static validatePermissionConditions(
    user: User,
    permissionCode: string,
    userPermissions: Permission[],
    context: any,
    allTeams: Team[],
    allDepartments: Department[]
  ): boolean {
    // 查找匹配的权限
    const matchingPermissions = userPermissions.filter(permission =>
      permission.code === permissionCode
    );
    
    if (matchingPermissions.length === 0) {
      return false;
    }
    
    // 检查每个匹配的权限
    for (const permission of matchingPermissions) {
      if (this.evaluatePermission(permission, user, context, allTeams, allDepartments)) {
        return true;
      }
    }
    
    return false;
  }

  /**
   * 评估单个权限
   */
  private static evaluatePermission(
    permission: Permission,
    user: User,
    context: any,
    allTeams: Team[],
    allDepartments: Department[]
  ): boolean {
    // 1. 检查权限作用域
    if (permission.scope && !this.checkPermissionScope(permission.scope, user, context, allTeams, allDepartments)) {
      return false;
    }
    
    // 2. 检查权限条件
    if (permission.conditions && permission.conditions.length > 0) {
      return this.checkPermissionConditions(permission.conditions, user, context);
    }
    
    // 如果没有特殊条件，权限有效
    return true;
  }

  /**
   * 检查权限作用域
   */
  private static checkPermissionScope(
    scope: string,
    user: User,
    context: any,
    allTeams: Team[],
    allDepartments: Department[]
  ): boolean {
    switch (scope) {
      case 'global':
        return true;
        
      case 'organization':
        // 检查组织级权限（如果有组织上下文）
        return context.organizationId === context.userOrganizationId;
        
      case 'department':
        // 检查部门级权限
        if (!user.departments?.length || !context.departmentId) {
          return false;
        }
        return user.departments.some(dept => dept.id === context.departmentId) ||
               this.isUserInParentDepartment(user, context.departmentId, allDepartments);
        
      case 'team':
        // 检查团队级权限
        if (!user.teams?.length || !context.teamId) {
          return false;
        }
        return user.teams.some(team => team.id === context.teamId);
        
      case 'owner':
        // 检查所有者权限
        return context.ownerId === user.id;
        
      case 'custom':
        // 自定义作用域通过条件来实现
        return true;
        
      default:
        return true;
    }
  }

  /**
   * 检查权限条件
   */
  private static checkPermissionConditions(
    conditions: any[],
    user: User,
    context: any
  ): boolean {
    for (const condition of conditions) {
      if (!this.evaluateCondition(condition, user, context)) {
        return false;
      }
    }
    return true;
  }

  /**
   * 评估单个条件
   */
  private static evaluateCondition(
    condition: any,
    user: User,
    context: any
  ): boolean {
    let actualValue: any;
    
    // 获取实际值
    if (condition.contextField) {
      actualValue = this.getNestedValue(user, condition.contextField) ||
                    this.getNestedValue(context, condition.contextField);
    } else {
      actualValue = context[condition.field];
    }
    
    // 执行条件比较
    return this.compareValues(actualValue, condition.operator, condition.value);
  }

  /**
   * 获取嵌套对象的值
   */
  private static getNestedValue(obj: any, path: string): any {
    return path.split('.').reduce((current, key) => current?.[key], obj);
  }

  /**
   * 比较值
   */
  private static compareValues(actual: any, operator: string, expected: any): boolean {
    switch (operator) {
      case '=':
        return actual === expected;
      case '!=':
        return actual !== expected;
      case '>':
        return actual > expected;
      case '<':
        return actual < expected;
      case '>=':
        return actual >= expected;
      case '<=':
        return actual <= expected;
      case 'in':
        return Array.isArray(expected) && expected.includes(actual);
      case 'not_in':
        return Array.isArray(expected) && !expected.includes(actual);
      case 'contains':
        return typeof actual === 'string' && typeof expected === 'string' && actual.includes(expected);
      default:
        return false;
    }
  }

  /**
   * 检查用户是否在父部门中
   */
  private static isUserInParentDepartment(
    user: User,
    targetDeptId: string,
    allDepartments: Department[]
  ): boolean {
    if (!user.departments?.length) {
      return false;
    }
    
    // 检查用户是否在目标部门的父部门中
    for (const userDept of user.departments) {
      if (this.isParentDepartment(userDept.id, targetDeptId, allDepartments)) {
        return true;
      }
    }
    
    return false;
  }
  /**
   * 检查是否为父部门
   */
  private static isParentDepartment(
    userDeptId: string,
    targetDeptId: string,
    allDepartments: Department[]
  ): boolean {
    const targetDept = this.findDepartmentById(targetDeptId, allDepartments);
    if (!targetDept) {
      return false;
    }
    
    // 递归检查父部门
    let currentDept = targetDept;
    while (currentDept.parentId) {
      if (currentDept.parentId === userDeptId) {
        return true;
      }
      const parentDept = this.findDepartmentById(currentDept.parentId, allDepartments);
      if (!parentDept) {
        break;
      }
      currentDept = parentDept;
    }
    
    return false;
  }
  
  /**
   * 检查用户是否拥有指定角色
   */
  static hasRole(
    user: User,
    roleCode: string,
    allTeams: Team[],
    allDepartments: Department[]
  ): boolean {
    // 检查直接角色
    if (user.roles?.some(role => role.code === roleCode)) {
      return true;
    }
    
    // 检查团队角色
    if (user.teams?.length) {
      for (const userTeam of user.teams) {
        const team = allTeams.find(t => t.id === userTeam.id);
        if (team) {
          // 团队角色检查逻辑已移除
        }
      }
    }
    
    // 检查部门角色
    if (user.departments?.length) {
      for (const userDept of user.departments) {
        const department = this.findDepartmentById(userDept.id, allDepartments);
        if (department) {
          // 部门角色检查逻辑已移除
        }
      }
    }
    
    return false;
  }
  
  /**
   * 获取团队的继承权限（包括父团队权限）
   * 注意：团队角色功能已移除，此方法保留以兼容现有代码
   */
  static getTeamInheritedRoles(
    team: Team,
    allTeams: Team[],
    visited: Set<string> = new Set()
  ): string[] {
    // 团队角色功能已移除，返回空数组
    return [];
  }
  
  /**
   * 根据ID查找部门（支持嵌套）
   */
  private static findDepartmentById(
    departmentId: string,
    departments: Department[]
  ): Department | undefined {
    for (const dept of departments) {
      if (dept.id === departmentId) {
        return dept;
      }
      
      if (dept.children) {
        const found = this.findDepartmentById(departmentId, dept.children);
        if (found) {
          return found;
        }
      }
    }
    
    return undefined;
  }
  
  /**
   * 获取部门的所有子部门ID
   */
  static getDepartmentChildrenIds(
    departmentId: string,
    allDepartments: Department[]
  ): string[] {
    const department = this.findDepartmentById(departmentId, allDepartments);
    if (!department) {
      return [];
    }
    
    const childrenIds: string[] = [];
    
    const collectChildren = (dept: Department) => {
      if (dept.children) {
        dept.children.forEach(child => {
          childrenIds.push(child.id);
          collectChildren(child);
        });
      }
    };
    
    collectChildren(department);
    return childrenIds;
  }
}

// 权限常量定义
export const PERMISSION_CATEGORIES = {
  USER: 'user',
  ROLE: 'role',
  TEAM: 'team',
  PERMISSION: 'permission',
  MENU: 'menu',
  SYSTEM: 'system',
  REPORT: 'report'
} as const;

export const PERMISSION_ACTIONS = {
  READ: 'read',
  WRITE: 'write',
  UPDATE: 'update',
  DELETE: 'delete',
  EXPORT: 'export',
  IMPORT: 'import',
  ASSIGN: 'assign',
  MANAGE: 'manage'
} as const;

// 预定义权限
export const PREDEFINED_PERMISSIONS: Omit<Permission, 'id' | 'createTime' | 'updateTime'>[] = [
  // 用户管理权限 - 基础权限
  { code: 'user:read', name: '查看用户', category: 'user', resource: 'user', action: 'read' },
  { code: 'user:write', name: '创建用户', category: 'user', resource: 'user', action: 'write' },
  { code: 'user:update', name: '编辑用户', category: 'user', resource: 'user', action: 'update' },
  { code: 'user:delete', name: '删除用户', category: 'user', resource: 'user', action: 'delete' },
  { code: 'user:export', name: '导出用户', category: 'user', resource: 'user', action: 'export' },
  
  // 用户管理权限 - 带条件的细粒度权限
  { 
    code: 'user:read:department', 
    name: '查看本部门用户', 
    category: 'user', 
    resource: 'user', 
    action: 'read',
    scope: 'department',
    description: '只能查看同部门的用户'
  },
  { 
    code: 'user:update:own', 
    name: '编辑个人信息', 
    category: 'user', 
    resource: 'user', 
    action: 'update',
    scope: 'owner',
    description: '只能编辑自己的用户信息'
  },
  { 
    code: 'user:update:subordinate', 
    name: '编辑下级用户', 
    category: 'user', 
    resource: 'user', 
    action: 'update',
    scope: 'custom',
    conditions: [
      { field: 'managerId', operator: '=', contextField: 'user.id', description: '只能编辑直接下属' }
    ],
    description: '只能编辑直接下属的用户信息'
  },
  
  // 角色管理权限
  { code: 'role:read', name: '查看角色', category: 'role', resource: 'role', action: 'read' },
  { code: 'role:write', name: '创建角色', category: 'role', resource: 'role', action: 'write' },
  { code: 'role:update', name: '编辑角色', category: 'role', resource: 'role', action: 'update' },
  { code: 'role:delete', name: '删除角色', category: 'role', resource: 'role', action: 'delete' },
  { code: 'role:assign', name: '分配角色', category: 'role', resource: 'role', action: 'assign' },
  
  // 团队管理权限
  { code: 'team:read', name: '查看团队', category: 'team', resource: 'team', action: 'read' },
  { code: 'team:write', name: '创建团队', category: 'team', resource: 'team', action: 'write' },
  { code: 'team:update', name: '编辑团队', category: 'team', resource: 'team', action: 'update' },
  { code: 'team:delete', name: '删除团队', category: 'team', resource: 'team', action: 'delete' },
  { code: 'team:manage', name: '管理团队成员', category: 'team', resource: 'team', action: 'manage' },
  
  // 权限管理权限
  { code: 'permission:read', name: '查看权限', category: 'permission', resource: 'permission', action: 'read' },
  { code: 'permission:write', name: '创建权限', category: 'permission', resource: 'permission', action: 'write' },
  { code: 'permission:update', name: '编辑权限', category: 'permission', resource: 'permission', action: 'update' },
  { code: 'permission:delete', name: '删除权限', category: 'permission', resource: 'permission', action: 'delete' },
  
  // 菜单管理权限
  { code: 'menu:read', name: '查看菜单', category: 'menu', resource: 'menu', action: 'read' },
  { code: 'menu:write', name: '创建菜单', category: 'menu', resource: 'menu', action: 'write' },
  { code: 'menu:update', name: '编辑菜单', category: 'menu', resource: 'menu', action: 'update' },
  { code: 'menu:delete', name: '删除菜单', category: 'menu', resource: 'menu', action: 'delete' },
  
  // 系统管理权限
  { code: 'system:read', name: '查看系统信息', category: 'system', resource: 'system', action: 'read' },
  { code: 'system:write', name: '修改系统配置', category: 'system', resource: 'system', action: 'write' },
  { code: 'system:log', name: '查看系统日志', category: 'system', resource: 'system', action: 'read' },
  { code: 'system:monitor', name: '系统监控', category: 'system', resource: 'system', action: 'read' },
];